<?php

class Admin_AacademicaController extends Zend_Controller_Action {

    public function init() {
        
    }

    public function preDispatch() {
        $auth = Zend_Auth::getInstance();
        if (!$auth->hasIdentity()) {
            $this->_helper->layout->disableLayout();
            $this->_redirect('/');
        } else {
            $identity = $auth->getIdentity();
            if ($identity['tipo_usuario'] != VirtualLabs_Admin_Usuario::ROL_ADMIN) {
                $this->_helper->layout->disableLayout();
                $this->_redirect('/');
            }
        }
        //fin de la autenicacion del usuario
    }

    public function indexAction() {
        
    }

    public function editAction() {
        $codigo_aacademica = $this->getRequest()->getParam("id");
        $this->view->codigoAreaAcademica = $codigo_aacademica;
        try {
            if (isset($codigo_aacademica)) {
                $aacademicaDao = new VirtualLabs_Admin_AreaAcademica();
                $aacademica = $aacademicaDao->getAreaAcademica(array('codigo_area_academica', 'nombre', 'descripcion'), array('codigo_area_academica' => array('criteria' => '=', 'value' => $codigo_aacademica)));
                $this->view->nombre = $aacademica['nombre'];
                $this->view->descripcion = $aacademica['descripcion'];
            }
        } catch (Exception $exc) {
            $debugLog = Zend_Registry::get(VirtualLabs_Common::DEBUG_LOG);
            $debugLog->debug($exc->getMessage());
            $debugLog->debug($exc->getTraceAsString());
        }
    }

    public function listAction() {
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout->disableLayout();
        $aaData = array();
        try {
            $area_academica = new Application_Model_AreaAcademica();
            $list = $area_academica->fetchList();
            $response = array();
            foreach ($list as $a) {
                $row = $a->toArray();
                $response[] = array("<input type='image' src='/images/delete.png' onclick='deleteArea({$row['codigo_area_academica']})' />",
                    "<a href='/admin/aacademica/edit/id/{$row['codigo_area_academica']}'>{$row['nombre']}</a>",
                    $row['descripcion']);
            }
            $aaData['aaData'] = $response;
        } catch (Exception $exc) {
            $debugLog = Zend_Registry::get(VirtualLabs_Common::DEBUG_LOG);
            $debugLog->debug($exc->getMessage());
            $debugLog->debug($exc->getTraceAsString());
            $aaData['error'] = $exc->getTraceAsString();
        }
        echo Zend_Json_Encoder::encode($aaData);
    }

    /**
     * 
     */
    public function deleteAction() {
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout->disableLayout();
        $codigo_aacademica = $this->getRequest()->getParam("id");
        $response = array();
        try {
            $codigoAreaAcademica = array('key' => 'codigo_area_academica', 'value' => $codigo_aacademica);
            $aacademicaDao = new VirtualLabs_Admin_AreaAcademica();
            $accountRest = new VirtualLabs_Rest_VirtualLabs_Account();
            $aacademica = $aacademicaDao->getAreaAcademica(array('codigo_area_academica', 'account_id'), array('codigo_area_academica' => array('criteria' => '=', 'value' => $codigo_aacademica)));

            $aacademicaDao->deleteAreaAcademica($codigoAreaAcademica);
            $accountRest->deleteAccount($aacademica['account_id']);
            $response['response'] = 'success';
        } catch (Exception $exc) {
            $debugLog = Zend_Registry::get(VirtualLabs_Common::DEBUG_LOG);
            $debugLog->debug($exc->getMessage());
            $debugLog->debug($exc->getTraceAsString());
            $response['response'] = 'error';
            if ($exc->getCode() == 23000) {
                $response['message'] = "Existe un Laboratorio asociado al Area Academica";
            } else {
                $response['message'] = $exc->getMessage();
            }
        }
        echo Zend_Json_Encoder::encode($response);
    }

    /**
     * 
     */
    public function saveAction() {
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout->disableLayout();
        $codigo_aacademica = $this->getRequest()->getParam("id");
        $nombre = $this->getRequest()->getParam("nombre");
        $descripcion = $this->getRequest()->getParam("descripcion");
        $response = array();
        try {
            $debugLog = Zend_Registry::get(VirtualLabs_Common::DEBUG_LOG);
            $debugLog->debug("Parametros: {$codigo_aacademica} ,{$nombre} , {$descripcion}");

            $aacademicaDao = new VirtualLabs_Admin_AreaAcademica();

            if (strlen($codigo_aacademica) > 0) {
                //Editar 
                $debugLog->debug("Estoy en editar");
                $data_aacademica = array('nombre' => $nombre, 'descripcion' => $descripcion);
                $codigoAreaAcademica = array("codigo_area_academica = ?" => $codigo_aacademica);
                $aacademicaDao->save($data_aacademica, $codigoAreaAcademica);
            } else {
                //Nuevo                
                $debugLog->debug("Estoy en nuevo");
                $accountRest = new VirtualLabs_Rest_VirtualLabs_Account();
                $nombre_alt = str_replace(" ", "", strtolower($nombre));
                $account = $accountRest->createAccount2($nombre_alt);
                $api_key = $account['register']['registeruserkeysresponse']['userkeys']['apikey'];
                $secret_key = $account['register']['registeruserkeysresponse']['userkeys']['secretkey'];
                $account_id = $account['createaccountresponse']['account']['id'];
                $password = md5($nombre_alt);
                $data_aacademica = array('nombre' => $nombre,
                    'descripcion' => $descripcion,
                    'api_key' => $api_key,
                    'secret_key' => $secret_key,
                    'account_id' => $account_id,
                    'password' => $password,
                    'username_account' => 'markosbenitez'); //mientras tanto
                //'username_account' => $nombre_alt);                                                
                $aacademicaDao->save($data_aacademica);
            }
            $response['response'] = 'success';
        } catch (Exception $exc) {
            $debugLog = Zend_Registry::get(VirtualLabs_Common::DEBUG_LOG);
            $debugLog->debug($exc->getMessage());
            $debugLog->debug($exc->getTraceAsString());
            $response['response'] = 'error';
            $response['message'] = $exc->getMessage();
        }
        echo Zend_Json_Encoder::encode($response);
    }

}